package com.yjf.demo.common;

import com.yjf.demo.basic.user.entity.User;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@RequiredArgsConstructor
public class SessionService {

    private final RedissonClient redissonClient;

    // 存储会话（有效期30分钟）
    public void saveUserSession(String sessionId, User user) {
        RBucket<User> bucket = redissonClient.getBucket(buildSessionKey(sessionId));
        bucket.set(user, Duration.ofMinutes(30));
    }

    // 获取并续期会话
    public User getUserWithRenewal(String sessionId) {
        RBucket<User> bucket = redissonClient.getBucket(buildSessionKey(sessionId));
        User user = bucket.get();
        if (user != null) {
            bucket.expire(Duration.ofMinutes(30)); // 重置过期时间
        }
        return user;
    }

    // 判断session是否存在
    public boolean isExist(String sessionId) {
        return redissonClient.getBucket(buildSessionKey(sessionId)).isExists();
    }

    // 删除会话
    public void deleteSession(String sessionId) {
        redissonClient.getBucket(buildSessionKey(sessionId)).delete();
    }

    // 获取session的过期时间
    public long getExpireTime(String sessionId) {
//        return redissonClient.getBucket(buildSessionKey(sessionId)).getExpireTime();

        // 本地的redis版本不支持直接查询 ExpireTime
        // 使用 TTL 命令替代（返回秒级剩余时间）
        long ttlSeconds = redissonClient.getBucket(buildSessionKey(sessionId)).remainTimeToLive();
        return System.currentTimeMillis() + ttlSeconds * 1000;
    }

    // 构建Redis键
    private String buildSessionKey(String sessionId) {
        return "user:session:" + sessionId;
    }
}
